package com.woniuxy.project115.kaer.platform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.project115.kaer.platform.entity.Account;
import com.woniuxy.project115.kaer.platform.entity.AccountRole;
import com.woniuxy.project115.kaer.platform.entity.Role;
import com.woniuxy.project115.kaer.platform.mapper.AccountMapper;
import com.woniuxy.project115.kaer.platform.mapper.AccountRoleMapper;
import com.woniuxy.project115.kaer.platform.mapper.RoleMapper;
import com.woniuxy.project115.kaer.platform.service.AccountRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author fyy
 * @since 2025年02月23日
 */
@Service
public class AccountRoleServiceImpl extends ServiceImpl<AccountRoleMapper, AccountRole> implements AccountRoleService {
    @Resource
    private AccountRoleMapper accountRoleMapper;
    @Resource
    private AccountMapper accountMapper;
    @Resource
    private RoleMapper roleMapper;
    @Override
    public void updateAccountRole(Integer accountId, Integer roleId) throws Exception {
        //查看是否有该账号
        final QueryWrapper<Account> accountQueryWrapper = new QueryWrapper<>();
        accountQueryWrapper.eq("id",accountId);
        Account account = accountMapper.selectOne(accountQueryWrapper);
        if(account == null){
            throw new Exception("账号不存在");
        }
        //查看是否有该角色
        final QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
        roleQueryWrapper.eq("id",roleId);
        Role role = roleMapper.selectOne(roleQueryWrapper);
        if(role == null){
            throw new Exception("角色不存在");
        }
        //更新角色
        final QueryWrapper<AccountRole> wrapper = new QueryWrapper<AccountRole>().eq("account_id", accountId);
        final AccountRole accountRole = accountRoleMapper.selectOne(wrapper);
        accountRole.setRoleId(roleId);
        accountRole.setCreatedTime(LocalDateTime.now());
        accountRoleMapper.updateById(accountRole);
    }
}
